package yolorpc.fault.retry;


import com.github.rholder.retry.*;
import lombok.extern.slf4j.Slf4j;
import yolorpc.model.RpcResponse;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author yolo
 * @Program RPC
 * @description 固定时间间隔 - 重试策略
 * @create 2025-05-27 17:23
 **/
@Slf4j
public class FixedIntervalRetryStrategy implements RetryStrategy{
    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class)
                .withWaitStrategy(WaitStrategies.fixedWait(3L, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .withRetryListener(new CustomRetryListener())
                .build();
        return retryer.call(callable);
    }

    // 自定义监听器
    private static class CustomRetryListener implements RetryListener {
        @Override
        public <V> void onRetry(Attempt<V> attempt) {
            log.info("重试次数 {}", attempt.getAttemptNumber());
        }
    }
}
